import json
import time

import pymysql

route_list = []

def app(path):
    def warpper(func):
        route_list.append((path,func))
        def inner():
            pass
        return inner
    return warpper


#  @app('路径')　将路径及其对应函数引用添加到路由列表中　　而非装饰作用  flask框架添加路由的方式
@app("/gettime.html")
def get_time():
    return time.ctime()

@app("/index.html")
def index():
    '''当前用户请求/index.html 执行当前函数'''
    # 1.将模板文件从磁盘读取到内存中
    with open("./template/index.html","r",encoding = "utf-8") as file:
        html_data = file.read()
    # 2.从数据库中读取数据
    conn = pymysql.connect(host = '192.168.199.132',port = 3306, user = 'root', password = 'mysql', db = 'stock_db', charset = 'utf8')
    cur = conn.cursor()
    cur.execute("select * from info")
    data = cur.fetchall()
    cur.close()
    conn.close()
    stock_data = ""
    for line in data:
        line_str = """<tr>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td>%s</td>
                    <td><input type="button" value="添加" id="toAdd" name="toAdd" systemidvaule="000007"></td>
            </tr>""" % line
        stock_data += line_str
    # 3.将模板文件进行替换（把占位符替换为用户所需要的数据）
    html_data = html_data.replace("{%content%}",stock_data)
    return html_data

@app("/center.html")
def center():
    with open("./template/center.html","r",encoding='utf-8') as file:
        html_data = file.read()
    html_data = html_data.replace("{%content%}","")
    return html_data

@app("/center_data.html")
def center_data():
    conn = pymysql.connect(host = '192.168.199.132',port = 3306, user = 'root', password = 'mysql', db = 'stock_db', charset = 'utf8')
    cur = conn.cursor()
    sql = "select i.code, i.short,i.chg,i.turnover,i.price,i.highs,focus.note_info from info i inner join focus on i.id = focus.info_id;"
    cur.execute(sql)
    data = cur.fetchall()
    cur.close()
    conn.close()
    data_list = list()
    for row in data:
        center_dict = dict()
        center_dict["code"] = row[0]
        center_dict["short"] = row[1]
        center_dict["chg"] = row[2]
        center_dict["turnover"] = row[3]
        center_dict["price"] = str(row[4])
        center_dict["highs"] = str(row[5])
        center_dict["note_info"] = row[6]
        data_list.append(center_dict)

    json_data = json.dumps(data_list,ensure_ascii=False)
    return json_data



def app(env):
    path_info = env["PATH_INFO"]
    print("框架收到动态资源请求 %s" % path_info)
    for path, func in route_list:
        if path == path_info:
            return '200OK',[("server","APP1.1")], func()
    else:
        return '404 NotFound',[("server","APP1.1")],"hello world"
